package com.hao.netty.server;

import com.hao.netty.handler.ChatServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * TODO
 *  netty 服务器端
 * @author 97472
 * @version 1.0
 * @date 2021/11/25 15:41
 */
public class NettyServer {
    public static void main(String[] args) {
            // 创建两个线程组 bossGroup和workerGroup
            // bossGroup用来处理连接，而workerGroup去真正的处理事件或者业务上的操作
            // 两个都是无限循环的
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {


            // 创建服务端的启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            // 使用链式编程进行对服务端进行配置
            serverBootstrap.group(bossGroup,workerGroup)// 将两个线程组配置到启动对象中去
                    .channel(NioServerSocketChannel.class)// 配置NioServerSocketChannel设置为服务端的通道
                    .option(ChannelOption.SO_BACKLOG,128)// 设置线程队列得到的连接数
                    .childOption(ChannelOption.SO_KEEPALIVE,true)// 设置保持活跃的连接状态
                    .childHandler(new ChatServerInitializer());

            System.out.println("服务器已经准备好..........");
            // 绑定一个端口并同步，生成一个ChannelFuture
            ChannelFuture channelFuture = serverBootstrap.bind(6789).sync();
            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (future.isSuccess()){
                        System.out.println("绑定端口成功!");
                    }else {
                        System.out.println("绑定端口失败!");
                    }

                }
            });
            // 对关闭的通道进行监听
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            进行关闭
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
        }
    }
}
